﻿using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using TelerikConnect.Models;
using TelerikConnect.Web.DBConnect;
using TelerikConnect.Web.ViewModels;

namespace TelerikConnect.Web.Controllers
{
    [Authorize]
    public class MessagesController : Controller
    {
        private readonly TelerikDb db = new TelerikDb();

        public ActionResult Inbox()
        {
            return View();
        }

        public ActionResult Sent()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Send()
        {
            return PartialView();
        }

        public ActionResult UnreadMessagesCount()
        {
            return Content((db.Messages.Count(m => m.Reciever.UserName == User.Identity.Name && !m.Read).ToString()));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Send(MessageSendViewModel message)
        {
            var reciever = db.UserProfiles.SingleOrDefault(u => u.UserName == message.RecieverUserName);
            ViewBag.Message = "There was a problem sending your message. Please try again.";

            if (reciever != null)
            {
                db.Messages.Add(new MessageModel
                    {
                        Title = message.Title,
                        Content = message.Content,
                        Read = false,
                        Reciever = reciever,
                        Sender = db.UserProfiles.First(u => u.UserName == User.Identity.Name),
                        SentTime = DateTime.Now
                    });
                db.SaveChanges();
                ViewBag.Message = string.Format("{0} has recieved your message.", message.RecieverUserName);
            }
            else
            {
                ViewBag.Message = string.Format("There is no user with the name {0}. Please try again.", message.RecieverUserName);
            }

            return PartialView();
        }

        public ActionResult Preview(int id)
        {
            var message = db.Messages.Where(m => m.Id == id && m.Sender.UserName == User.Identity.Name).SingleOrDefault();

            if (message != null)
            {
                var msg = db.Messages.Where(m => m.Id == id && m.Sender.UserName == User.Identity.Name).Select(
                    m => new MessageSendViewModel
                    {
                        Title = m.Title,
                        RecieverUserName = m.Sender.UserName,
                        Content = m.Content
                    }
                    ).SingleOrDefault();

                return View("View", msg);
            }

            return Redirect("/");
        }

        public ActionResult View(int id)
        {
            var message = db.Messages.Where(m => m.Id == id && m.Reciever.UserName == User.Identity.Name).SingleOrDefault();

            if (message != null)
            {
                message.Read = true;
                db.SaveChanges();

                var msg = db.Messages.Where(m => m.Id == id && m.Reciever.UserName == User.Identity.Name).Select(
                    m => new MessageSendViewModel
                    {
                        Title = m.Title,
                        RecieverUserName = m.Sender.UserName,
                        Content = m.Content
                    }
                    ).Single();

                return View(msg);
            }

            return Redirect("/");
        }

        public ActionResult Messages([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetMessages().ToDataSourceResult(request));
        }

        public ActionResult GetSent([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetMessagesSent().ToDataSourceResult(request));
        }

        private IEnumerable<MessagePreviewViewModel> GetMessagesSent()
        {
            return db.Messages.Where(m => m.Sender.UserName == User.Identity.Name).Select(
                        m => new MessagePreviewViewModel
                        {
                            Title = m.Title,
                            Read = m.Read,
                            SentTime = m.SentTime,
                            Id = m.Id,
                            Sender = new UserBasicAvatarViewModel
                            {
                                FirstName = m.Reciever.FirstName,
                                LastName = m.Reciever.LastName,
                                UserName = m.Reciever.UserName,
                                Avatar = m.Reciever.Avatar
                            }
                        }
                        );
        }

        private IEnumerable<MessagePreviewViewModel> GetMessages()
        {
            return db.Messages.Where(m => m.Reciever.UserName == User.Identity.Name).Select(
                        m => new MessagePreviewViewModel
                        {
                            Title = m.Title,
                            Read = m.Read,
                            SentTime = m.SentTime,
                            Id = m.Id,
                            Sender = new UserBasicAvatarViewModel
                            {
                                FirstName = m.Sender.FirstName,
                                LastName = m.Sender.LastName,
                                UserName = m.Sender.UserName,
                                Avatar = m.Sender.Avatar
                            }
                        }
                        );
        }
    }
}